package pl.engine.model
{
	import pl.engine.model.vo.BaseMapTile;
	import pl.engine.model.vo.obstacle.IBaseObstacle;
	import pl.engine.ui.gui.panel.InfoPanel;
	import pl.error.InternalError;
	import pl.textures.game.ISingleTexture;

	import flash.geom.Point;

	/**
	 * @author michalr
	 */
	public class Model implements IModel
	{
		private var terrain:Array;
		private var _obstacles:Vector.<IBaseObstacle> = new Vector.<IBaseObstacle>();
		private var terrainReadyHandler:Function;
		private static var gridSize:Point;
		private static var secureFunction:Function;
		
		public function Model( tW:uint, tH:uint, iW:uint, iH:uint )
		{
			if (secureFunction == null)
			{
				throw new Error( InternalError.CREATION_ERROR );
			}
			MapGrid.TILE_W = tW;
			MapGrid.TILE_H = tH;
			MapGrid.ISO_W = iW;
			MapGrid.ISO_H = iH;
		}

		public static function factory( isoTextureBase:ISingleTexture ):IModel
		{
			secureFunction = function():void
			{
			};
			var tileSize:uint = Math.sqrt( Math.pow( isoTextureBase.textureSize.y, 2 ) + Math.pow( isoTextureBase.textureSize.y, 2 ) );
			return new Model( tileSize, tileSize, isoTextureBase.textureSize.x, isoTextureBase.textureSize.y );
		}

		public function setTerrain( arr:Array ):void
		{
			trace( MapGrid.TILE_W, MapGrid.TILE_H, MapGrid.ISO_W, MapGrid.ISO_H );
			terrain = arr;
			Model.gridSize = new Point( terrain[0]['length'], terrain.length );
			MapGrid.GRID_W_COUNT = getGridSize().x;
			MapGrid.GRID_H_COUNT = getGridSize().y;
			if (terrainReadyHandler != null) terrainReadyHandler();
		}

		public function setTerrainReadyHandler( handler:Function ):void
		{
			terrainReadyHandler = handler;
		}

		public function getTileById( hID:uint, vID:uint ):BaseMapTile
		{
			try
			{
				terrain[vID][hID];
			}
			catch (e:Error)
			{
				trace( 'Erro', vID, hID );
			}
			return terrain[vID][hID];
		}

		public static function getGridSize():Point
		{
			return gridSize;
		}

		public function get obstacles():Vector.<IBaseObstacle>
		{
			return _obstacles;
		}

		public function set obstacle( obs:IBaseObstacle ):void
		{
			_obstacles.push( obs );
		}
	}
}
